﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Data.Services.Client;

using WebRole1.DataService;
using System.Data.Objects;


namespace WebRole1
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        static DateTime PersistCookie = DateTime.Now.AddYears(10);

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                HtmlGenericControl body = (HtmlGenericControl)Page.Master.FindControl("MainBody");

                string defaultCitySearchName = "Vancouver British Columbia";
                string queryCity = Request.QueryString["city"];
                if (queryCity != null)
                {
                    defaultCitySearchName = queryCity;
                }
                else
                {
                    HttpCookie currentCityCookieName = Request.Cookies.Get("currentCityCookieName");
                    if (currentCityCookieName != null && !string.IsNullOrEmpty(currentCityCookieName.Value))
                    {
                        defaultCitySearchName = currentCityCookieName.Value.Replace("%20", " ");
                    }
                }

                decimal latitude, longtitude;

                try
                {
                    using (LocationsDBEntities locEntities = new LocationsDBEntities())
                    {
                        var city = locEntities.City.First(f => f.SearchName == defaultCitySearchName);
                        TextBoxCurrentCityId.Text = city.CityID.ToString();
                        latitude = city.Lat;
                        longtitude = city.Lon;
                    }
                }
                catch
                {
                    defaultCitySearchName = "Vancouver British Columbia";
                    using (LocationsDBEntities locEntities = new LocationsDBEntities())
                    {
                        var city = locEntities.City.First(f => f.SearchName == defaultCitySearchName);
                        TextBoxCurrentCityId.Text = city.CityID.ToString();
                        latitude = city.Lat;
                        longtitude = city.Lon;
                    }
                }

                TextBoxCurrentCityName.Text = defaultCitySearchName;

                string script = String.Format("GetMap({1},{2});InitializeCity(\"{0}\", {1}, {2}, {3});",
                    defaultCitySearchName, latitude, longtitude, TextBoxCurrentCityId.Text);

                body.Attributes.Add("onload", script);

                ButtonChangeCityHotCat_Click(null, null);

                HttpCookie lastPageCookie = new HttpCookie("LastPage");
                lastPageCookie.Value = "Default.aspx";
                lastPageCookie.Expires = PersistCookie;
                Response.Cookies.Add(lastPageCookie);
            }
        }

        public UserTbl GetCurrentUser(LocationsDBEntities locEntities)
        {
            string userId = "";
            Label mpLabel = (Label)Master.FindControl("LabelCurrentLiveUser");
            if (mpLabel != null)
            {
                userId = mpLabel.Text;
            }

            return Utils.GetCurrentUser(locEntities, userId);
        }

        protected void ButtonComment_Click(object sender, EventArgs e)
        {
            using (LocationsDBEntities locEntities = new LocationsDBEntities())
            {
                UserTbl user = GetCurrentUser(locEntities);
                int locID = Convert.ToInt32(TextBoxCommentLocID.Text);

                var loc = locEntities.Location.First(f => f.LocationID == locID);

                var myComment = new Comment();

                myComment.UserTbl = user;
                myComment.Location = loc;
                myComment.CommentDate = DateTime.Now.ToUniversalTime();
                myComment.Rating = Convert.ToInt32(DropDownListRating.Text);
                myComment.CommentText = TextBoxComment.Text;

                locEntities.AddToComment(myComment);

                locEntities.SaveChanges();

                //calculate average
                loc.Comment.Load();
                var q = loc.Comment.Select(o => o.Rating).Average();
                loc.Rating = Convert.ToInt32(q);
                locEntities.SaveChanges();
            }

        }

        protected void ButtonPublish_Click(object sender, EventArgs e)
        {
            using (LocationsDBEntities locEntities = new LocationsDBEntities())
            {
                UserTbl user = GetCurrentUser(locEntities);

                //note, can also use TextBoxCurrentCityId to get the city
                string cityname = TextBoxCurrentCityName.Text.Trim();
                var city = locEntities.City.First(f => f.SearchName == cityname);

                Location myLoc = null;
                int locID = 0;

                if (String.IsNullOrEmpty(TextBoxLocationID.Text))
                {
                    myLoc = new Location();
                    myLoc.Rating = 0; //initial value always 0, as unrated
                }
                else
                {
                    locID = Convert.ToInt32(TextBoxLocationID.Text);
                    myLoc = locEntities.Location.First(f => f.LocationID == locID);
                    myLoc.UserTblReference.Load();
                    if (myLoc.UserTbl.UserID != user.UserID)
                    {
                        throw new Exception("Only user published this location can modify it.");
                    }
                }

                myLoc.City = city;
                myLoc.UserTbl = user;
                myLoc.CreateDatetime = DateTime.Now.ToUniversalTime();

                myLoc.Name = TextBoxLocationName.Text;
                myLoc.Descr = TextBoxLocationdesc.Text;
                myLoc.Address1 = TextBoxAddress1.Text;
                myLoc.Address2 = TextBoxAddress2.Text;
                myLoc.CreateDatetime = DateTime.Now.ToUniversalTime();
                myLoc.Lat = Convert.ToDecimal(TextBoxLatitude.Text);
                myLoc.Lon = Convert.ToDecimal(TextBoxLongtitude.Text);
                myLoc.Url = TextLocationUrl.Text;
                myLoc.NeedEmailUpdate = CheckBoxEmailNotify.Checked;

                myLoc.UrlLink1 = TextBoxUrlLink1.Text;
                myLoc.UrlLink1Mark = TextBoxUrlLink1Mark.Text;
                myLoc.UrlLink2 = TextBoxUrlLink2.Text;
                myLoc.UrlLink2Mark = TextBoxUrlLink2Mark.Text;
                myLoc.Phone = TextBoxPhone.Text;
                myLoc.ImageUrl = TextBoxImageUrl.Text;

                if (locID == 0)
                {
                    locEntities.AddToLocation(myLoc);
                }

                locEntities.SaveChanges();

                if (locID > 0)
                {
                    //category relationship exist, remove it first
                    myLoc.RelationLocCat.Load();
                    foreach (RelationLocCat rel in myLoc.RelationLocCat.ToArray())
                    {
                        locEntities.DeleteObject(rel);
                    }
                    locEntities.SaveChanges();
                }

                //save cateogry/location relationship
                char[] sep = { ',' };
                foreach (string catId in TextBoxCategory.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries))
                {
                    int catIdInt = Convert.ToInt32(catId);
                    Category myCat = locEntities.Category.First(f => f.CategoryID == catIdInt);
                    RelationLocCat newRel = new RelationLocCat();
                    newRel.Location = myLoc;
                    newRel.Category = myCat;

                    locEntities.AddToRelationLocCat(newRel);
                }
                locEntities.SaveChanges();
            }
        }

        protected void ButtonChangeCityHotCat_Click(object sender, EventArgs e)
        {
            using (LocationsDBEntities locEntities = new LocationsDBEntities())
            {
                int layerId = 10;

                //note, can also use TextBoxCurrentCityId to get the city
                string cityname = TextBoxCurrentCityName.Text.Trim();
                var city = locEntities.City.First(f => f.SearchName == cityname);

                city.Category.Load();
                PlaceHolderCityHotCat.Controls.Clear();

                if (city.Category.Count == 0)
                {
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("<span>No Links configured</span><br />"));
                }

                List<string> ogdiList = new List<string>();
                List<string> geoRssList = new List<string>();
                List<string> kmlList = new List<string>();
                List<string> csvList = new List<string>();

                foreach (Category cat in city.Category.OrderBy(f => f.CategoryName))
                {
                    if (string.IsNullOrEmpty(cat.CategorySvcUrl) || string.IsNullOrEmpty(cat.CategorySvcUrlType))
                    {
                        continue;
                    }

                    string funcName = "";

                    List<string> myList = null;

                    if (cat.CategorySvcUrlType == "kml")
                    {
                        funcName = "CheckKmlFile";
                        myList = kmlList;
                    }
                    else if (cat.CategorySvcUrlType == "ogdi")
                    {
                        funcName = "CheckOGDIService";
                        myList = ogdiList;
                    }
                    else if (cat.CategorySvcUrlType == "csv")
                    {
                        funcName = "CheckCsvFile";
                        myList = csvList;
                    }
                    else if (cat.CategorySvcUrlType == "georss")
                    {
                        funcName = "CheckGeoRss";
                        myList = geoRssList;
                    }
                    else
                    {
                        continue; //unknown type, don't show the link directly
                    }

                    string imageLink = "";
                    if (!string.IsNullOrEmpty(cat.MapIconUrl))
                    {
                        imageLink = string.Format("<img alt='{0}' src='{1}'/>", cat.CategoryName, cat.MapIconUrl);
                    }
                    //<li><span>
                    //   <input id="CheckBoxWebRole1" type="checkbox" onclick="CheckOGDIService('http://vancouverdataservice.cloudapp.net/v1/vancouver/CommunityCentres/', layerWebRole1, this.checked);" />Community
                    //   Centers
                    //   <img alt="Community Center" src="Images/WebRole1A.PNG" />
                    //</span></li>

                    string linkControl = String.Format("<span>&nbsp;&nbsp;<input type='checkbox' onclick='{0}(\"{1}\", {2}, this.checked, \"{3}\");' />{4}{5}</span><br/>\n",
                             funcName, cat.CategorySvcUrl, layerId++, cat.MapIconUrl, cat.CategoryName, imageLink);
                    myList.Add(linkControl);
                }

                if (ogdiList.Count() > 0)
                {
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("<p><span class='linkType'>OGDI</span><br/>"));
                    foreach (string linkControl in ogdiList)
                    {
                        PlaceHolderCityHotCat.Controls.Add(new LiteralControl(linkControl));
                    }
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("</p>"));
                }

                if (kmlList.Count() > 0)
                {
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("<p><span class='linkType'>KML</span><br/>"));
                    foreach (string linkControl in kmlList)
                    {
                        PlaceHolderCityHotCat.Controls.Add(new LiteralControl(linkControl));
                    }
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("</p>"));
                }

                if (geoRssList.Count() > 0)
                {
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("<p><span class='linkType'>GeoRSS</span><br/>"));
                    foreach (string linkControl in geoRssList)
                    {
                        PlaceHolderCityHotCat.Controls.Add(new LiteralControl(linkControl));
                    }
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("</p>"));
                }

                if (csvList.Count() > 0)
                {
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("<p><span class='linkType'>CSV</span><br/>"));
                    foreach (string linkControl in csvList)
                    {
                        PlaceHolderCityHotCat.Controls.Add(new LiteralControl(linkControl));
                    }
                    PlaceHolderCityHotCat.Controls.Add(new LiteralControl("</p>"));
                }


            }
        }


    }
}
